package top.rainbowecho.article.controller;

import com.google.common.collect.ImmutableMap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.rainbowecho.article.service.IManagementService;
import top.rainbowecho.common.util.CommonUtil;
import top.rainbowecho.common.util.ResultKey;
import top.rainbowecho.model.percona.Management;

import java.util.List;
import java.util.Map;

/**
 * @author rainbow
 * @since 2020/10/10 16:03
 */
@RestController
@RequestMapping("/manage")
@Slf4j
public class ManageController {
    private IManagementService managementService;

    @Autowired
    public void setManagementService(IManagementService managementService) {
        this.managementService = managementService;
    }

    /**
     * 添加页面的管理元素
     *
     * @param management 管理元素数据
     * @param bindingResult 参数绑定结果
     * @return 添加成功的管理元素
     */
    @PostMapping
    public ResponseEntity<Map<String, Object>> addManagementEle(Management management, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return CommonUtil.handleValidateError(bindingResult);
        }

        this.managementService.saveManagement(management);
        ImmutableMap<String, Object> result = ImmutableMap.of(ResultKey.DATA, management);
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    /**
     * 返回所有页面的管理元素
     *
     * @return 所有管理元素
     */
    @GetMapping
    public ResponseEntity<Map<String, Object>> getAllWebManagement() {
        List<Map<String, String>> managements = this.managementService.getAllManagement();
        ImmutableMap<String, Object> result = ImmutableMap.of(ResultKey.DATA, managements);
        return new ResponseEntity<>(result, HttpStatus.OK);
    }
}
